<template>
  <div class="login_container">
    <div class="login_title">用户登录界面</div>
    <div class="login_box">
      <!-- 头像区域 -->
      <div class="avatar_box">
        <img src="../assets/images/dinosaur.jpg" alt="" />
      </div>
      <!-- 登录表单区域 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px" class="login_form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model.trim="loginForm.username" prefix-icon="iconfont icon-gerenxinxi"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="iconfont icon-tianchongxing-" type="password"
            @keyup.enter.native="login" :show-password="true"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input size="normal" type="text" v-model="loginForm.code" auto-complete="off" placeholder="点击图片更换验证码"
            @keydown.enter.native="submitLogin" style="width: 250px"></el-input>
          <img :src="vcUrl" @click="updateVerifyCode" alt="" style="cursor: pointer">
        </el-form-item>
        <!-- 按钮区域 -->
        <el-form-item class="btns">
          <a href="https://gitee.com/oauth/authorize?client_id=67f906c59abadfb89bceaad09debdb6a3fd009bdfbbeec9ee3002ab4a24f9fb8&redirect_uri=http://localhost:8889/api/oauth2.0/weibo/success&response_type=code"
            title="Gitee登录" target="_blank">
            <svg t="1686041211368" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="1834" width="30" height="30">
              <path
                d="M512 1024C229.222 1024 0 794.778 0 512S229.222 0 512 0s512 229.222 512 512-229.222 512-512 512z m259.149-568.883h-290.74a25.293 25.293 0 0 0-25.292 25.293l-0.026 63.206c0 13.952 11.315 25.293 25.267 25.293h177.024c13.978 0 25.293 11.315 25.293 25.267v12.646a75.853 75.853 0 0 1-75.853 75.853h-240.23a25.293 25.293 0 0 1-25.267-25.293V417.203a75.853 75.853 0 0 1 75.827-75.853h353.946a25.293 25.293 0 0 0 25.267-25.292l0.077-63.207a25.293 25.293 0 0 0-25.268-25.293H417.152a189.62 189.62 0 0 0-189.62 189.645V771.15c0 13.977 11.316 25.293 25.294 25.293h372.94a170.65 170.65 0 0 0 170.65-170.65V480.384a25.293 25.293 0 0 0-25.293-25.267z"
                fill="#C71D23" p-id="1835"></path>
            </svg>
          </a>
          <el-button type="primary" @click="dialog = true">注册</el-button>
          <el-button type="primary" @click="login" :loading="loginLoading">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
    <!--    粒子插件特效-->
    <vue-particles class="login-bg" color="#39AFFD" :particleOpacity="0.7" :particlesNumber="100" shapeType="circle"
      :particleSize="4" linesColor="#8DD1FE" :linesWidth="1" :lineLinked="true" :lineOpacity="0.4" :linesDistance="150"
      :moveSpeed="3" :hoverEffect="true" hoverMode="grab" :clickEffect="true" clickMode="push">
    </vue-particles>
    <div class="footer">
      <span style="font-weight: bold;color:white;margin-bottom: 10px">
        登录页面切换
        <!-- <i class="iconfont icon-haoyou " @click="goUser"></i> -->
      </span>
      <span>
        <i class="iconfont icon-guanliyuan" @click="goManage"></i>
      </span>
    </div>
    <div class="footer2">

      <el-popover placement="top-start" :width="150" trigger="hover">
        <p slot="reference"> 联系作者| ©2023-2024 By 小帅<br /> </p>
        <img src="../assets/images/dinosaur.jpg" style="height: 100px; width: 100px" />
      </el-popover>
    </div>
    <div>
      <el-drawer title="用户注册" :before-close="handleClose" :visible.sync="dialog" direction="ltr"
        custom-class="demo-drawer" ref="drawer">
        <div class="demo-drawer__content">
          <el-form :model="ruleForm" status-icon :rules="loginFormRules" ref="ruleForm" label-width="100px"
            class="demo-ruleForm">

            <div class="avatar_box">
              <img :src="defaultPicture" alt="" />
            </div>
              <div>
              <el-upload action="http://mengshuai-test.oss-cn-beijing.aliyuncs.com" :data="dataObj" list-type="picture"
                :multiple="false" :show-file-list="showFileList" :file-list="fileList" :before-upload="beforeUpload"
                :on-remove="handleRemove" :on-success="handleUploadSuccess" >
                <el-button size="small" type="primary">点击上传头像</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
              </el-upload>
              
            </div>
            <!-- 隐藏注册头像 -->
            <input type="hidden" v-model="ruleForm.picture">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="cardName">
              <el-input v-model="ruleForm.cardName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="cardNumber">
              <el-input v-model.number="ruleForm.cardNumber"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <el-input v-model="ruleForm.code" autocomplete="off"></el-input>
            </el-form-item>

          </el-form>
          <div class="demo-drawer__footer">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">{{ loading ? '退出中 ...' : '提交'
              }}</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>




</template>
<script>
   import {policy} from './policy'
   import { getUUID } from './Utils'
import axios from 'axios'
export default {
  // 头像、使用oss对象存储表单
  name: 'singleUpload',
  props: {
    value: String
  },
  computed: {
   
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== '') {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }]
    },
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined;
      },
      set: function (newValue) {
      }
    },

    //
  },
  data() {
    var card = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          console.log(String(value).length);
          if (String(value).length != 11) {
            callback(new Error('手机号为11位'));
          } else {
            callback();
          }
        }
      }, 500);
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      // 头像、使用oss对象存储表单
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: '',
        // callback:'',
      },
      dialogVisible: false,
      //头像默认值
      defaultPicture: require('../assets/images/dinosaur.jpg') ,
      //
      dialog: false,
      loading: false,
      direction: 'rtl',
      //验证码
      vcUrl: 'http://localhost:8889/api/verifyCode?time=' + new Date(),
      //注册表单
      ruleForm: {
        picture: "",
        username: "",
        cardName: "",
        password: "",
        checkPass: "",
        cardNumber: "",
        code: "",
      },
      //登录表单
      loginForm: {
        username: "相思断红肠",
        password: "123456",
        code: "",
      },

      //登录表单规则的验证对象
      loginFormRules: {
        password: [
          { validator: validatePass, required: true, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, required: true, trigger: 'blur' }
        ],
        cardNumber: [
          { validator: card, required: true, trigger: 'blur' }
        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        cardName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      loginLoading: false
    };
  },
  methods: {
    //头像、使用oss对象存储表单
    getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
},
    emitInput(val) {
      this.defaultPicture = val;
    },
    handleRemove(file, fileList) {
      this.emitInput('');
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {

      let _self = this;
      return new Promise((resolve, reject) => {

        
        policy().then(response => {
          console.log(response);
     
          _self.dataObj.policy = response.policy;
          _self.dataObj.signature = response.signature;
          _self.dataObj.ossaccessKeyId = response.accessid;
          _self.dataObj.key = response.dir + getUUID() + '_${filename}';
          _self.dataObj.dir = response.dir;
          _self.dataObj.host = response.host;
          
       
          resolve(true)
    
        }).catch(err => {
     
          reject(false)
        })

      })
 
    },
    handleUploadSuccess(res, file) {
      this.$message.success("上传成功...");
      console.log("上传成功...")
      this.showFileList = true;
      this.fileList.pop();
      this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}", file.name) });
      this.emitInput(this.fileList[0].url);
      console.log(this.fileList[0].url);
    },

    //
    updateVerifyCode() {
      this.vcUrl = 'http://localhost:8889/api/verifyCode?time=' + new Date();
    },
    //注册表单提交
    submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        this.ruleForm.picture = this.defaultPicture;
        if (valid) {
          axios
            .post("user/register", this.ruleForm)
            .then((response) => {
              console.log(response.data);
              if (response.data.status !== 200) {
                console.log(response.data.map);
                return this.$message.error(response.data.msg);
              }
              this.cancelForm();
              // console.log(res);
              this.$message.success(response.data.msg);
            })
            .catch((err) => {
              console.log(err);
            });

        } else {
          alert("未按规范填写注册条件，请重新填写");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm("注册未完成，是否要退出？")
        .then((_) => {
          this.loading = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
              this.ruleForm = {};
            }, 400);
          }, 200);
        })
        .catch((_) => { });
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      this.ruleForm = {};
      clearTimeout(this.timer);
    },

    // //
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },
    login() {
      this.$refs.loginFormRef.validate(async (valid) => {
        // console.log(valid);
        //如果表单验证无效，直接返回
        if (!valid) {
          return;
        }
        this.loginLoading = true;
        // 进行md5加密
        const salt = "xiaobaitiao";
        const username = this.loginForm.username;
        const password = this.loginForm.password;
        const code = this.loginForm.code;
        //向数据库发送axios请求，如果登录成功，就跳转
        const { data: res } = await this.$http.post(
          "user/login",
          {
            username,
            password,
            code,
          },
          { withCredentials: true }
        );
        if (res.status !== 200) {
          this.loginLoading = false;
          this.vcUrl = 'http://localhost:8889/api/verifyCode?time=' + new Date();
          return this.$message.error(res.msg);
        }
        // console.log(res);
        this.$message.success("登录成功");
        this.loginLoading = false;
        window.sessionStorage.setItem("token", res.map.token);
        window.sessionStorage.setItem("userId", res.map.id);
        this.$router.push("/home"); //跳转到home页面下
      });
    },
    othlogin() {
      axios.get('https://gitee.com/oauth/authorize?client_id=67f906c59abadfb89bceaad09debdb6a3fd009bdfbbeec9ee3002ab4a24f9fb8&redirect_uri=http://localhost:8889/api/oauth2.0/weibo/success&response_type=code')
        .then(function (response) {
          console.log(response.data);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    goUser() {
      this.$router.push("/login");
    },
    goManage() {
      this.$router.push("/loginmanage");
    },
  },
};
</script>

<style lang="less" scoped>
.footer2 {
  position: absolute;
  bottom: 0px;
  left: 35%;
  color: #ccc;

  a {
    color: #ccc;
  }
}

.login_container {
  // background-color: #2b4b6b;
  background: url(../assets/images/digitalCityMin.jpg) no-repeat 0px 0px;
  background-size: cover;
  height: 100%;
}

.el-drawer .avatar_box {
  width: 130px;
  height: 130px;
  border: 1px solid #eee;
  border-radius: 50%;
  padding: 10px;
  background-color: #fff;

  img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
}

.login_box {
  height: 330px;
  width: 450px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    width: 130px;
    height: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}

.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}

.btns {
  display: flex;
  justify-content: flex-end;
}

.login_title {
  position: relative;
  top: 5%;
  font-size: 36px;
  color: white;
  text-align: center;
  font-weight: 700;
  //控制字体间距
  letter-spacing: 10px;
}

.footer {
  display: flex;
  position: absolute;
  flex-direction: column;
  bottom: 0;
  right: 0;
  width: 100px;
  height: 120px;

  // background-color: pink;
  span {
    // width: 100%;
    // background-color: red;
    text-align: center;
  }
}
</style>
